//
//  GiftThatViewController.m
//  GiftThat
//
//  Created by ChuXiang on 16/1/6.
//  Copyright © 2016年 ChuXiang. All rights reserved.
//

#import "GiftThatViewController.h"
#import "SFGiftThatCollectionViewCell.h"
#import "SFSelectionCellModel.h"
#import "SFGiftOtherCollectionViewCell.h"
#import "SFGiftLBoViewController.h"
#import "SFJumpWebViewController.h"
#import "SFUnderLBoViewController.h"
#import "SFUnderLBoCollectionViewCell.h"
#import "TheMenuView.h"
#import "CXAddAndDeletaView.h"


#define kColor [UIColor colorWithRed:255 / 255.0 green:64 / 255.0 blue:64 / 255.0 alpha:1.0]

@interface GiftThatViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic,strong) UICollectionView *CollectionView;
@property (nonatomic, strong) NSMutableArray *navArray;
@property (nonatomic,strong)  UIScrollView *scrollView;
@property (nonatomic, retain) NSMutableArray *buttonArray;
@property (nonatomic, retain) NSMutableArray *idArray;
@property (nonatomic, strong) TheMenuView *menuView;
@property (nonatomic, strong) NSMutableArray *addOrDeleteArray;
@property (nonatomic, strong) NSMutableArray *relodataArray;
@property (nonatomic, strong) NSMutableArray *modelArray;
@property (nonatomic,strong) UIImageView *imageView;
@property (nonatomic,strong) UIButton *button;

@end

@implementation GiftThatViewController

- (void)dealloc {
  
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
        [self GetData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.relodataArray = [NSMutableArray arrayWithCapacity:0];
    self.relodataArray = [self getLocalData];

    self.modelArray = [NSMutableArray arrayWithCapacity:0];
    self.navigationItem.title = @"礼物说";
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self GetCollectionview];
    self.navArray = [NSMutableArray array];
    self.buttonArray = [NSMutableArray array];
    self.idArray = [NSMutableArray array];

 
    [self creatScrollView];
    [self dongHua];
    
//    创建scrollview旁边的button按钮
    self.button = [UIButton buttonWithType:UIButtonTypeSystem];
    self.button.tag = 100001;
    self.button.frame = CGRectMake(self.view.width - 30 , 0, 30, 40);
    self.button.backgroundColor = [UIColor whiteColor];
    [self.button setImage:[[UIImage imageNamed:@"xiala"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [self.button addTarget:self action:@selector(buttonPress:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.button];
   

    [self getAddOrDeleteData];
    NSArray *chaChe = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *chaCheStr = [chaChe lastObject];
    for (int i = 0; i < self.addOrDeleteArray.count; i++) {
        
        NSString *songPath = [NSString stringWithFormat:@"%@/Caches/button%d.plist", chaCheStr, i];
        //    归档
        [NSKeyedArchiver archiveRootObject:self.addOrDeleteArray[i] toFile:songPath];
    }
    

    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"Color"] isEqualToString:@"BlackColor"]) {
        self.CollectionView.backgroundColor = [UIColor colorWithRed:37 / 255.0 green:36 / 255.0 blue:40 / 255.0 alpha:1.0];
        self.scrollView.backgroundColor = [UIColor colorWithRed:35 / 255.0 green:34 / 255.0 blue:38 / 255.0 alpha:1.0];
        self.button.backgroundColor = [UIColor colorWithRed:35 / 255.0 green:34 / 255.0 blue:38 / 255.0 alpha:1.0];
        
    }else{
        self.CollectionView.backgroundColor = [UIColor whiteColor];
        self.scrollView.backgroundColor = [UIColor whiteColor];
        self.button.backgroundColor = [UIColor whiteColor];
    }
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(changeDays:) name:@"Color" object:nil];
    

}



-(void)dongHua{
    self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0,0 , 80, 80)];
    self.imageView.backgroundColor = [UIColor blackColor];
    self.imageView.alpha = 0.5;
    self.imageView.center = CGPointMake(self.view.width / 2, self.view.height / 2 - 80);
    NSMutableArray*muArray = [NSMutableArray array];
    for (int i = 0; i < 15; i++) {
        [muArray addObject:[UIImage imageNamed:[NSString stringWithFormat:@"loading_%d",i]]];
    }
    [self.imageView setAnimationImages:muArray];
    [self.imageView setAnimationDuration:3];
    [self.imageView startAnimating];
    [self.view addSubview:self.imageView];
    
}


-(void)buttonPress:(UIButton *)sender{

    self.menuView = [[TheMenuView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height)];
    self.menuView.dataSource = self.addOrDeleteArray;
    [self.menuView showInView:self.view];
    
    __weak GiftThatViewController *weakSelf = self;
    self.menuView.relodataBlock = ^(NSMutableArray *data){
        [weakSelf.scrollView removeAllSubviews];
        weakSelf.relodataArray = data;
        [weakSelf GetData];
        

        
        UIButton *button = (UIButton *)[weakSelf.view viewWithTag:100];
        [weakSelf buttonDidPress:button];
        [weakSelf.CollectionView setContentOffset:CGPointMake(0, 0)];
        [weakSelf.scrollView setContentOffset:CGPointMake(0, 0)];
        [weakSelf.CollectionView reloadData];

    };
    

}

- (void)getAddOrDeleteData{
    self.addOrDeleteArray = [NSMutableArray arrayWithCapacity:0];
    [CXNetWorkTool getWithUrl:kAddOrDeleteButtonGetUrl parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
        if (result) {
            NSDictionary *data = result[@"data"];
            NSArray *array = data[@"candidates"];
            for (NSDictionary *dic in array) {
                CXAddOrDeleteModel *model = [[CXAddOrDeleteModel alloc] initWithDictionary:dic];
                [self.addOrDeleteArray addObject:model];
            }
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self.imageView stopAnimating];
                [self.imageView removeFromSuperview];
                
            });

            

        }
    } fail:^(NSError *error) {
      
    }];
}

 // 首页上面一条导航栏
- (void)GetData{
    [self.scrollView removeAllSubviews];
    [self.modelArray removeAllObjects];

    [CXNetWorkTool getWithUrl:kGiftSayNavGETURL parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
         NSArray *array = [[NSArray alloc]initWithArray:[[result objectForKey:@"data"] objectForKey:@"channels"]];
        for (NSDictionary *dic in array) {
            SFSelectionCellModel *data = [[SFSelectionCellModel alloc]initWithDictionary:dic];
            [self.navArray addObject:data.name];
            [self.idArray addObject:dic[@"id"]];
            [self.modelArray addObject:data];
          
        }

        if (self.relodataArray.count > 0) {
            [self.idArray removeAllObjects];
            [self.navArray removeAllObjects];
            self.navArray = [self getLocalData];
;
            for (int i = 0; i < self.navArray.count; i++) {
                for (int j = 0; j < self.modelArray.count; j++) {
                    if ([self.navArray[i] isEqualToString:[self.modelArray[j] name]]) {


                        [self.idArray addObject:[self.modelArray[j] NewId]];
                    }
                }
            }
        }
            self.scrollView.contentSize = CGSizeMake(self.view.width / 5 * self.navArray.count, 0);
            [self.buttonArray removeAllObjects];
            for (int i = 0; i < self.navArray.count; i++) {
                UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
                button.frame = CGRectMake(self.view.width / 5 * i, 5, self.view.width / 5, 30);
                button.tag = 100 + i;
//                button.backgroundColor = [UIColor clearColor];
               
             
                if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"Color"] isEqualToString:@"BlackColor"]) {
                    
                    if (button.tag == 100) {
                         [button setTitleColor: [UIColor redColor]forState:UIControlStateNormal];
                        button.titleLabel.font = [UIFont systemFontOfSize:16];
                        [button.titleLabel setFont:[UIFont fontWithName:@"FZLanTingHei-EL-GBK" size:16]];
                    }else{
                        [button setTitleColor: [UIColor whiteColor]forState:UIControlStateNormal];
                    }
                 
                    
                }else{
                if (button.tag == 100) {
                    button.titleLabel.font = [UIFont systemFontOfSize:16];
                [button.titleLabel setFont:[UIFont fontWithName:@"FZLanTingHei-EL-GBK" size:16]];
                    [button setTintColor:[UIColor redColor]];
                }else{
                [button setTitleColor: [UIColor blackColor]forState:UIControlStateNormal];
                }
                }
                    [self.buttonArray addObject:button];
         
                [button setTitle:self.navArray[i] forState:UIControlStateNormal];
                [button addTarget:self action:@selector(buttonDidPress:) forControlEvents:UIControlEventTouchUpInside];
                [self.scrollView addSubview:button];

        }
        [self.CollectionView setContentOffset:CGPointMake(0, 0)];
            [self.CollectionView reloadData];
        
        
    } fail:^(NSError *result) {
        
    }];
}
// 标题栏button点击collectionView切换item
-(void)buttonDidPress:(UIButton *)button {
    
    self.CollectionView.contentOffset = CGPointMake((button.tag - 100) * self.view.width, 0);
 
    for (UIButton *buttons in self.buttonArray) {
        buttons.titleLabel.font = [UIFont systemFontOfSize:15];
//        [buttons setTitleColor: [UIColor blackColor]forState:UIControlStateNormal];
        
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"Color"] isEqualToString:@"BlackColor"]) {
            [buttons setTitleColor: [UIColor whiteColor]forState:UIControlStateNormal];
            
        }else{
            [buttons setTitleColor: [UIColor blackColor]forState:UIControlStateNormal];
        }
    }
    [button setTitleColor:kColor forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:16];
   
}
// collectionView切换item标题栏跟着改变选中位置
//-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
//    for (int i = 0 ; i < self.buttonArray.count; i++) {
//        UIButton *button = (UIButton *)[self.view viewWithTag:100+i];
//        button.titleLabel.font = [UIFont systemFontOfSize:15];
//        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    }
//}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
  
    CGFloat x = scrollView.contentOffset.x/self.view.width;
    
    if (scrollView == self.CollectionView) {
        for (int i = 0; i < self.buttonArray.count; i++) {
            UIButton *button = [self.buttonArray objectAtIndex:i];
            
            if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"Color"] isEqualToString:@"BlackColor"]) {
                [button setTitleColor: [UIColor whiteColor]forState:UIControlStateNormal];
                
            }else{
               [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            }
            
            button.titleLabel.font = [UIFont systemFontOfSize:15];
            button.backgroundColor = [UIColor clearColor];
        }
        UIButton * button = [self.buttonArray objectAtIndex:x];
        [button setTitleColor:kColor forState:UIControlStateNormal];
        [button.titleLabel setFont:[UIFont systemFontOfSize:16]];
        
    
        
        if (x < 3) {

            if (x > 1) {
                [self.scrollView setContentOffset:CGPointMake(75 * (x-2), 0) animated:YES];
            }
           
        } else if (x >= 3 && x < self.buttonArray.count - 2) {

             [self.scrollView setContentOffset:CGPointMake(75 * (x-2), 0) animated:YES];
            
        } else {

            
        }
        
    }
    
    
    
}


#pragma mark - 创建scrollView

-(void)creatScrollView {
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.width - 20, 40)];

    self.scrollView.backgroundColor = [UIColor whiteColor];
    self.scrollView.alwaysBounceVertical = NO;
    self.scrollView.directionalLockEnabled = YES;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    
    [self.view addSubview:self.scrollView];
}



- (void)GetCollectionview{
    UICollectionViewFlowLayout *FlowLayout = [[UICollectionViewFlowLayout alloc]init];
    FlowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    FlowLayout.itemSize = CGSizeMake(self.view.width, self.view.height);
    FlowLayout.minimumInteritemSpacing = CGFLOAT_MIN;
    FlowLayout.minimumLineSpacing = CGFLOAT_MIN;
    self.CollectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:FlowLayout];
    self.CollectionView.delegate = self;
    self.CollectionView.dataSource = self;
    self.CollectionView.bounces = NO;
    self.CollectionView.pagingEnabled = YES;
    self.CollectionView.backgroundColor = [UIColor whiteColor];
    [self.CollectionView registerClass:[SFGiftThatCollectionViewCell class] forCellWithReuseIdentifier:@"CollectionViewCellIdentifier"];
    [self.CollectionView registerClass:[SFGiftOtherCollectionViewCell class] forCellWithReuseIdentifier:@"SFGiftOtherCollectionViewCellIdentifier"];
    self.CollectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.CollectionView];
    
    
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
 
    return self.navArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.item == 0) {
        SFGiftThatCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionViewCellIdentifier" forIndexPath:indexPath];
        cell.delegate = self;
        [cell.tableView reloadData];
        return cell;
    }
    SFGiftOtherCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SFGiftOtherCollectionViewCellIdentifier" forIndexPath:indexPath];

    cell.row = self.idArray[indexPath.item];
    cell.delegate = self;
    [cell.tableview reloadData];

    return cell;
  
}
//协议轮播跳转
-(void)LBoPassByValue:(SFGiftSayScrollModel *)model{
   
    SFGiftLBoViewController *LBoViewController = [[SFGiftLBoViewController alloc]initWithModel:model];
    
    [self.navigationController pushViewController:LBoViewController animated:YES];
    
        CATransition *animation = [CATransition animation];
        animation.duration = 2.0f;
        [animation setType:@"rippleEffect"];
    
        [self.navigationController.view.layer addAnimation:animation forKey:nil];
    

}
//跳转web
-(void)tableviewJump:(NSString *)url{
    SFJumpWebViewController *JumpWebView = [[SFJumpWebViewController alloc]initWithURL:url];
    [self.navigationController pushViewController:JumpWebView animated:YES];
 
    
}
//首页以外页面的跳转到web
-(void)tableviewOtherJump:(NSString *)url{
    SFJumpWebViewController *JumpWebView = [[SFJumpWebViewController alloc]initWithURL:url];
    [self.navigationController pushViewController:JumpWebView animated:YES];
  
}

//轮播图下面的collectionview跳转
-(void)UnderLBo:(NSString *)url{
    SFUnderLBoViewController *UnderLBoViewController = [[SFUnderLBoViewController alloc]initWithURL:url];
    [self.navigationController pushViewController:UnderLBoViewController animated:YES];
  
    
}

- (NSMutableArray *)getLocalData{
 
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)firstObject];
    NSString *newFielPath = [documentsPath stringByAppendingPathComponent:@"/mydata.txt"];
    NSMutableArray *plistArray = [NSMutableArray arrayWithContentsOfFile:newFielPath];
        
    return plistArray;
    
}

- (void) changeDay:(NSNotification *)message {
    if ([message.object isEqualToString:@"BlackColor"]) {
        self.CollectionView.backgroundColor = [UIColor colorWithRed:35 / 255.0 green:34 / 255.0 blue:38 / 255.0 alpha:1.0];
          self.scrollView.backgroundColor = [UIColor colorWithRed:35 / 255.0 green:34 / 255.0 blue:38 / 255.0 alpha:1.0];
        self.button.backgroundColor = [UIColor colorWithRed:35 / 255.0 green:34 / 255.0 blue:38 / 255.0 alpha:1.0];
    }else {
        self.CollectionView.backgroundColor = [UIColor whiteColor];
          self.scrollView.backgroundColor = [UIColor whiteColor];
        self.button.backgroundColor = [UIColor whiteColor];
    }
    [self.CollectionView reloadData];

    
}
- (void) changeDays:(NSNotification *)message {
    if ([message.object isEqualToString:@"RedColor"]) {
        self.navigationController.navigationBar.barTintColor  = [UIColor colorWithRed:255 / 255.0 green:38 / 255.0 blue:56 / 255.0 alpha:1.0];
        self.tabBarController.tabBar.barTintColor = [UIColor whiteColor];
        
        
    }else if([message.object isEqualToString:@"GreenColor"]) {
        self.navigationController.navigationBar.barTintColor  = [UIColor greenColor];
        self.tabBarController.tabBar.barTintColor = [UIColor whiteColor];
        
        
    }else if([message.object isEqualToString:@"OrangeColor"]) {
        self.navigationController.navigationBar.barTintColor  = [UIColor orangeColor];
        self.tabBarController.tabBar.barTintColor = [UIColor whiteColor];
        
        
    }else if([message.object isEqualToString:@"PinkColor"]) {
        self.navigationController.navigationBar.barTintColor  = [UIColor colorWithRed:238 / 255.0 green:61 / 255.0 blue: 89 / 255.0 alpha:1.0];
        self.tabBarController.tabBar.barTintColor = [UIColor whiteColor];
        
    }else {
        self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
        self.tabBarController.tabBar.barTintColor = [UIColor blackColor];

    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
